package com.dbexposer.db.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.sql.DataSource;

import org.apache.ddlutils.Platform;
import org.apache.ddlutils.PlatformFactory;
import org.apache.ddlutils.model.Database;
import org.apache.ddlutils.model.Table;

import com.dbexposer.db.info.DBEntityInfo;

public class DBUtils {

	/**
	 * @param dataSource
	 * @param name
	 * @param catalog
	 * @param schema
	 * @param tableTypes
	 * @return entities list, sorted by table schema and table names.
	 */
	public static final List<DBEntityInfo> getEntitiesInfo(DataSource dataSource, String name, 
			String catalog, String schema, String[] tableTypes) {
		
		List<DBEntityInfo> infos = new ArrayList<DBEntityInfo>();
		Database database = readDatabase(dataSource, name, catalog, schema, tableTypes);
		Table[] tables = database.getTables();
		
		for (Table table : tables) {
			infos.add(new DBEntityInfo(table));
		}
		
		sortBySchemaAndTableNames(infos);
		return infos;
	}

	private static void sortBySchemaAndTableNames(List<DBEntityInfo> infos) {

		Collections.sort(infos, new Comparator() {

			public int compare(Object arg0, Object arg1) {
				
				DBEntityInfo entity0 = (DBEntityInfo) arg0;
				DBEntityInfo entity1 = (DBEntityInfo) arg1;
				
				String comparable0 = (entity0.getSchema() + "." + entity0.getName()).toUpperCase();
				String comparable1 = (entity1.getSchema() + "." + entity1.getName()).toUpperCase();
				
				return comparable0.compareTo(comparable1);
			}
			
		});
		
	}

	// FIXME ADD MORE PARAMETERS AND OVERLOADED METHODS ACCORDING TO DB TYPES
	public static final List<DBEntityInfo> getEntitiesInfo(DataSource dataSource) {
		return getEntitiesInfo(dataSource, null, null, null, null);
	}
	
	private static Database readDatabase(DataSource dataSource, String name, String catalog, String schema, String[] tableTypes)
	{
		Platform platform = PlatformFactory.createNewPlatformInstance(dataSource);
		return platform.readModelFromDatabase(name, catalog, schema, tableTypes);
	}
}
